package com.apes.framework.plugin.esb.processor.jpa;

import com.apes.framework.util.JpaUtil;
import com.apes.framework.jpa.repository.CustomRepository;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.Request;
import com.apes.framework.plugin.esb.processor.AbstractChainProcessor;
import lombok.Data;
import org.springframework.data.domain.PageRequest;
import org.springframework.util.StringUtils;

import java.util.Map;

/**
 * 功能：FindOneProcessor
 *
 * @author xul
 * @create 2018-07-11 9:50
 */
@Data
public class FindOneProcessor<T extends Request, R> extends AbstractChainProcessor<T, R> {

    private String repository = null;

    @Override
    protected R doProcess(T source) {
        if (StringUtils.isEmpty(this.repository)) throw new RuntimeException("repository 不允许为空！");
        CustomRepository repository = JpaUtil.getRepositoryByName(this.repository);
        Map m = source.getMap();
        if (m.containsKey("condition") || m.containsKey("group")) {
            return (R) repository.findAll(JpaDsl.build(source, false), PageRequest.of(0, 1)).getContent().stream().findFirst().orElse(null);
        }
        return (R) repository.findOne(JpaDsl.toCriteria(source.getMap())).orElse(null);
    }
}
